var crypto = require('crypto');
var Promise = require('bluebird');
var config = require('../../config');

var RANDOM_LEN = 10;

var _genRandomString = function(callback) {
  crypto.randomBytes(RANDOM_LEN, (err, buf) => {
    if (err) {
    	return callback(err);
    }
    return callback(null, buf.toString('base64'));
  });
};

var _genUserKey = function(id, callback) {

	var cipher = crypto.createCipher('aes192', config.aeskey);
  	_genRandomString(function(err, str) {
	    if (err) {
	      return callback && callback(err);
	    }
	    var encrypted = cipher.update(id + '/' + str, 'utf8', 'hex');
	    encrypted += cipher.final('hex');
	    return callback && callback(null, encrypted);
  	});
};

var initUser = function(id) {
  return new Promise(function(resolve, reject) {
    _genUserKey(id, function(err, key) {
      if (err) {
        return reject(err);
      }
      return resolve(key);
    });
  });
};

exports.initUser = initUser;